package cn.iocoder.yudao.module.devicemanager.controller.admin.ui;

import cn.iocoder.yudao.module.signature.appconnect.jaxrs.DevicesResource;
import cn.iocoder.yudao.module.signature.appconnect.model.*;
import cn.iocoder.yudao.module.signature.appconnect.util.AppleConnectUtil;
import cn.iocoder.yudao.module.signature.appconnect.util.ServiceProxyFactory;
import cn.iocoder.yudao.module.signature.appconnect.util.TokenUtil;
import lombok.extern.slf4j.Slf4j;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.dnd.*;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
public class DeviceManagerUI extends JFrame {
    private JTextField userIdField;
    private JTextField keyIdField;
    private JButton selectP8Button;
    private JButton confirmButton;
    private JTable deviceTable;
    private DefaultTableModel tableModel;
    private JButton enableButton;
    private JButton disableButton;
    private String p8FilePath;
    private String token;
    private JLabel statusLabel;
    private JDialog loadingDialog;

    public DeviceManagerUI() {
        setTitle("设备管理工具");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        initComponents();
    }

    private void initComponents() {
        // 创建主面板
        JPanel mainPanel = new JPanel(new BorderLayout());

        // 顶部输入区域改为垂直排列
        JPanel inputPanel = new JPanel();
        inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.Y_AXIS));

        // 第一行：用户ID和KeyID
        JPanel idPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        idPanel.add(new JLabel("用户ID:"));
        userIdField = new JTextField(20);
        idPanel.add(userIdField);
        idPanel.add(new JLabel("KeyID:"));
        keyIdField = new JTextField(20);
        idPanel.add(keyIdField);
        inputPanel.add(idPanel);

        // 第二行：文件选择区域
        JPanel p8Panel = new JPanel(new BorderLayout());
        p8Panel.setBorder(BorderFactory.createTitledBorder("拖拽P8文件到这里或点击选择"));
        p8Panel.setPreferredSize(new Dimension(400, 60));
        p8Panel.setMaximumSize(new Dimension(Integer.MAX_VALUE, 80));
        p8Panel.setBackground(new Color(240, 240, 240));
        new DropTarget(p8Panel, new DropTargetListener() {
            @Override
            public void dragEnter(DropTargetDragEvent dtde) {
                if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
                    dtde.acceptDrag(DnDConstants.ACTION_COPY);
                }
            }
            @Override public void dragOver(DropTargetDragEvent dtde) {}
            @Override public void dropActionChanged(DropTargetDragEvent dtde) {}
            @Override public void dragExit(DropTargetEvent dte) {}
            @Override
            public void drop(DropTargetDropEvent dtde) {
                try {
                    dtde.acceptDrop(DnDConstants.ACTION_COPY);
                    List<File> files = (List<File>) dtde.getTransferable().getTransferData(DataFlavor.javaFileListFlavor);
                    if (!files.isEmpty()) {
                        File file = files.get(0);
                        if (file.getName().toLowerCase().endsWith(".p8")) {
                            p8FilePath = file.getAbsolutePath();
                            JOptionPane.showMessageDialog(DeviceManagerUI.this, "已选择文件: " + p8FilePath);
                        } else {
                            JOptionPane.showMessageDialog(DeviceManagerUI.this, "请选择.p8文件");
                        }
                    }
                } catch (Exception e) {
                    log.error("处理拖拽文件失败", e);
                    JOptionPane.showMessageDialog(DeviceManagerUI.this, "处理文件失败: " + e.getMessage());
                }
            }
        });
        selectP8Button = new JButton("选择P8文件");
        p8Panel.add(selectP8Button, BorderLayout.CENTER);
        inputPanel.add(p8Panel);

        // 第三行：查询按钮
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        confirmButton = new JButton("查询");
        buttonPanel.add(confirmButton);
        inputPanel.add(buttonPanel);

        mainPanel.add(inputPanel, BorderLayout.NORTH);

        // 创建表格
        String[] columnNames = {"设备类型", "设备状态", "数量"};
        tableModel = new DefaultTableModel(columnNames, 0);
        deviceTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(deviceTable);
        mainPanel.add(scrollPane, BorderLayout.CENTER);

        // 创建底部面板
        JPanel bottomPanel = new JPanel(new BorderLayout());
        
        // 创建状态标签
        statusLabel = new JLabel("就绪");
        bottomPanel.add(statusLabel, BorderLayout.CENTER);

        // 创建底部操作按钮面板
        JPanel bottomButtonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        enableButton = new JButton("启用所有设备");
        disableButton = new JButton("禁用所有设备");
        bottomButtonPanel.add(enableButton);
        bottomButtonPanel.add(disableButton);
        bottomPanel.add(bottomButtonPanel, BorderLayout.SOUTH);

        mainPanel.add(bottomPanel, BorderLayout.SOUTH);

        // 添加事件监听器
        selectP8Button.addActionListener(e -> selectP8File());
        confirmButton.addActionListener(e -> loadDevices());
        enableButton.addActionListener(e -> updateDeviceStatus(true));
        disableButton.addActionListener(e -> updateDeviceStatus(false));

        // 初始状态下禁用按钮
        enableButton.setEnabled(false);
        disableButton.setEnabled(false);

        add(mainPanel);
    }

    private void showLoading(String message) {
        loadingDialog = new JDialog(this, "处理中", false);
        loadingDialog.setLayout(new BorderLayout());
        
        JPanel panel = new JPanel(new BorderLayout(10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        
        JLabel loadingLabel = new JLabel(message);
        loadingLabel.setHorizontalAlignment(SwingConstants.CENTER);
        panel.add(loadingLabel, BorderLayout.CENTER);
        
        loadingDialog.add(panel);
        loadingDialog.pack();
        loadingDialog.setLocationRelativeTo(this);
        loadingDialog.setVisible(true);
    }

    private void hideLoading() {
        if (loadingDialog != null) {
            loadingDialog.dispose();
            loadingDialog = null;
        }
    }

    private void selectP8File() {
        JFileChooser fileChooser = new JFileChooser();
        int result = fileChooser.showOpenDialog(this);
        if (result == JFileChooser.APPROVE_OPTION) {
            File selectedFile = fileChooser.getSelectedFile();
            p8FilePath = selectedFile.getAbsolutePath();
            JOptionPane.showMessageDialog(this, "已选择文件: " + p8FilePath);
        }
    }

    private void loadDevices() {
        try {
            String userId = userIdField.getText().trim();
            String keyId = keyIdField.getText().trim();

            if (userId.isEmpty() || keyId.isEmpty() || p8FilePath == null) {
                JOptionPane.showMessageDialog(this, "请填写所有必要信息");
                return;
            }

            // 获取token
            token = TokenUtil.generateToken(userId, keyId, new File(p8FilePath));

            // 获取设备列表
            Map<String, List<Device>> devices = AppleConnectUtil.getAllDevices(token);

            // 清空表格
            tableModel.setRowCount(0);

            // 按设备类型和状态统计
            devices.forEach((deviceType, deviceList) -> {
                Map<DeviceAttributes.Status, Long> statusCount = deviceList.stream()
                        .collect(Collectors.groupingBy(
                                device -> device.getAttributes().getStatus(),
                                Collectors.counting()
                        ));

                statusCount.forEach((status, count) -> {
                    tableModel.addRow(new Object[]{deviceType, status.value(), count});
                });
            });

            // 启用操作按钮
            enableButton.setEnabled(true);
            disableButton.setEnabled(true);

        } catch (Exception e) {
            log.error("加载设备失败", e);
            JOptionPane.showMessageDialog(this, "加载设备失败: " + e.getMessage());
        }
    }

    private void updateDeviceStatus(boolean enable) {
        int confirm = JOptionPane.showConfirmDialog(this,
                "确定要" + (enable ? "启用" : "禁用") + "所有设备吗？",
                "确认操作",
                JOptionPane.YES_NO_OPTION);

        if (confirm == JOptionPane.YES_OPTION) {
            try {
                // 获取所有设备
                Map<String, List<Device>> devices = AppleConnectUtil.getAllDevices(token);
                
                // 计算总设备数
                int totalDevices = devices.values().stream()
                        .mapToInt(List::size)
                        .sum();

                // 显示loading对话框
                showLoading("正在" + (enable ? "启用" : "禁用") + "设备，请稍候...");

                // 创建线程池，使用固定大小的线程池，线程数设为CPU核心数
                int processors = Runtime.getRuntime().availableProcessors();
                ExecutorService executorService = Executors.newFixedThreadPool(processors);
                CountDownLatch latch = new CountDownLatch(totalDevices);

                // 提交所有设备更新任务到线程池
                for (List<Device> deviceList : devices.values()) {
                    for (Device device : deviceList) {
                        executorService.submit(() -> {
                            try {
                                log.info("更新设备: " + device.getId());
                                DeviceUpdateRequest request = new DeviceUpdateRequest();
                                DeviceUpdateRequestData data = new DeviceUpdateRequestData();
                                data.setId(device.getId());
                                data.setType("devices");

                                DeviceUpdateRequestDataAttributes attributes = new DeviceUpdateRequestDataAttributes();
                                attributes.setStatus(enable ?
                                        DeviceUpdateRequestDataAttributes.Status.ENABLED :
                                        DeviceUpdateRequestDataAttributes.Status.DISABLED);

                                data.setAttributes(attributes);
                                request.setData(data);

                                // 调用API更新设备状态
                                DevicesResource devicesResource = ServiceProxyFactory.getInstance()
                                        .createServiceProxy(DevicesResource.class, token);
                                devicesResource.updateDevice(device.getId(), request);

                                latch.countDown();
                            } catch (Exception e) {
                                log.error("更新设备状态失败: " + device.getId(), e);
                                latch.countDown();
                            }
                        });
                    }
                }

                // 等待所有任务完成
                executorService.shutdown();
                executorService.awaitTermination(30, TimeUnit.MINUTES);

                // 隐藏loading对话框
                SwingUtilities.invokeLater(() -> {
                    hideLoading();
                    statusLabel.setText("操作完成");
                    JOptionPane.showMessageDialog(this, "操作完成");
                    // 重新加载设备列表
                    loadDevices();
                });

            } catch (Exception e) {
                log.error("更新设备状态失败", e);
                SwingUtilities.invokeLater(() -> {
                    hideLoading();
                    JOptionPane.showMessageDialog(this, "更新设备状态失败: " + e.getMessage());
                });
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            DeviceManagerUI ui = new DeviceManagerUI();
            ui.setVisible(true);
        });
    }
}